#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
技术分析系统 - 第三步执行模块
对筛选出的候选股票进行深度技术分析
"""

import sys
import os
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from real_data_fetcher import RealDataFetcher
from simple_technical_analysis import SimpleTechnicalAnalysis

class TechnicalAnalysisSystem:
    """技术分析系统"""
    
    def __init__(self):
        self.data_fetcher = RealDataFetcher()
        self.technical_analyzer = SimpleTechnicalAnalysis()
        
    def print_header(self, title):
        """打印标题"""
        print(f"\n{'='*80}")
        print(f"📈 {title}")
        print(f"{'='*80}")
        
    def load_screening_results(self, filename="screening_results.csv"):
        """加载筛选结果"""
        try:
            df = pd.read_csv(filename)
            return df.to_dict('records')
        except Exception as e:
            print(f"加载筛选结果失败: {e}")
            return []
            
    def get_historical_data(self, stock_code, days=120):
        """获取历史数据"""
        try:
            data = self.data_fetcher.get_stock_data(stock_code, days)
            if data is not None and not data.empty:
                return data
            return None
        except Exception as e:
            print(f"获取 {stock_code} 历史数据失败: {e}")
            return None
            
    def calculate_technical_indicators(self, stock_data):
        """计算技术指标"""
        try:
            indicators = {}
            
            # 移动平均线
            indicators['MA5'] = self.technical_analyzer.calculate_ma(stock_data['close'], 5)
            indicators['MA10'] = self.technical_analyzer.calculate_ma(stock_data['close'], 10)
            indicators['MA20'] = self.technical_analyzer.calculate_ma(stock_data['close'], 20)
            indicators['MA60'] = self.technical_analyzer.calculate_ma(stock_data['close'], 60)
            
            # 指数移动平均线
            indicators['EMA12'] = self.technical_analyzer.calculate_ema(stock_data['close'], 12)
            indicators['EMA26'] = self.technical_analyzer.calculate_ema(stock_data['close'], 26)
            
            # RSI
            indicators['RSI'] = self.technical_analyzer.calculate_rsi(stock_data['close'])
            
            # MACD
            macd_data = self.technical_analyzer.calculate_macd(stock_data['close'])
            indicators['MACD'] = macd_data['macd']
            indicators['MACD_Signal'] = macd_data['signal']
            indicators['MACD_Histogram'] = macd_data['histogram']
            
            # 布林带
            bollinger_data = self.technical_analyzer.calculate_bollinger_bands(stock_data['close'])
            indicators['BB_Upper'] = bollinger_data['upper']
            indicators['BB_Middle'] = bollinger_data['middle']
            indicators['BB_Lower'] = bollinger_data['lower']
            
            return indicators
            
        except Exception as e:
            print(f"计算技术指标失败: {e}")
            return {}
            
    def analyze_trend_direction(self, stock_data, indicators):
        """分析趋势方向"""
        try:
            current_price = stock_data['close'].iloc[-1]
            ma5_current = indicators['MA5'].iloc[-1] if not indicators['MA5'].empty else current_price
            ma20_current = indicators['MA20'].iloc[-1] if not indicators['MA20'].empty else current_price
            ma60_current = indicators['MA60'].iloc[-1] if not indicators['MA60'].empty else current_price
            
            # 趋势判断
            if current_price > ma5_current > ma20_current > ma60_current:
                trend = "强烈上升"
                trend_score = 90
            elif current_price > ma5_current > ma20_current:
                trend = "上升"
                trend_score = 70
            elif current_price > ma20_current:
                trend = "震荡偏多"
                trend_score = 60
            elif current_price < ma5_current < ma20_current < ma60_current:
                trend = "强烈下降"
                trend_score = 10
            elif current_price < ma5_current < ma20_current:
                trend = "下降"
                trend_score = 30
            else:
                trend = "震荡"
                trend_score = 50
                
            return {
                'trend': trend,
                'trend_score': trend_score,
                'current_price': current_price,
                'ma5': ma5_current,
                'ma20': ma20_current,
                'ma60': ma60_current
            }
            
        except Exception as e:
            print(f"分析趋势方向失败: {e}")
            return {'trend': '未知', 'trend_score': 50}
            
    def analyze_momentum(self, indicators):
        """分析动量指标"""
        try:
            rsi_current = indicators['RSI'].iloc[-1] if not indicators['RSI'].empty else 50
            macd_current = indicators['MACD'].iloc[-1] if not indicators['MACD'].empty else 0
            macd_signal = indicators['MACD_Signal'].iloc[-1] if not indicators['MACD_Signal'].empty else 0
            
            # RSI分析
            if rsi_current > 70:
                rsi_signal = "超买"
                rsi_score = 20
            elif rsi_current > 50:
                rsi_signal = "偏强"
                rsi_score = 70
            elif rsi_current > 30:
                rsi_signal = "中性"
                rsi_score = 50
            else:
                rsi_signal = "超卖"
                rsi_score = 80
                
            # MACD分析
            if macd_current > macd_signal > 0:
                macd_signal_desc = "金叉向上"
                macd_score = 80
            elif macd_current > macd_signal:
                macd_signal_desc = "多头强势"
                macd_score = 70
            elif macd_current < macd_signal < 0:
                macd_signal_desc = "死叉向下"
                macd_score = 20
            elif macd_current < macd_signal:
                macd_signal_desc = "空头强势"
                macd_score = 30
            else:
                macd_signal_desc = "震荡"
                macd_score = 50
                
            return {
                'rsi_value': rsi_current,
                'rsi_signal': rsi_signal,
                'rsi_score': rsi_score,
                'macd_signal': macd_signal_desc,
                'macd_score': macd_score,
                'momentum_score': (rsi_score + macd_score) / 2
            }
            
        except Exception as e:
            print(f"分析动量指标失败: {e}")
            return {'momentum_score': 50}
            
    def analyze_support_resistance(self, stock_data, indicators):
        """分析支撑阻力位"""
        try:
            current_price = stock_data['close'].iloc[-1]
            bb_upper = indicators['BB_Upper'].iloc[-1] if not indicators['BB_Upper'].empty else current_price * 1.05
            bb_lower = indicators['BB_Lower'].iloc[-1] if not indicators['BB_Lower'].empty else current_price * 0.95
            
            # 近期高低点
            recent_data = stock_data.tail(20)
            resistance_level = recent_data['high'].max()
            support_level = recent_data['low'].min()
            
            # 价格位置分析
            price_position = (current_price - bb_lower) / (bb_upper - bb_lower) * 100
            
            if price_position > 80:
                position_desc = "接近阻力位"
                position_score = 30
            elif price_position > 60:
                position_desc = "偏强区域"
                position_score = 70
            elif price_position > 40:
                position_desc = "中性区域"
                position_score = 60
            elif price_position > 20:
                position_desc = "偏弱区域"
                position_score = 40
            else:
                position_desc = "接近支撑位"
                position_score = 80
                
            return {
                'support_level': support_level,
                'resistance_level': resistance_level,
                'bb_upper': bb_upper,
                'bb_lower': bb_lower,
                'price_position': price_position,
                'position_desc': position_desc,
                'position_score': position_score
            }
            
        except Exception as e:
            print(f"分析支撑阻力位失败: {e}")
            return {'position_score': 50}
            
    def calculate_technical_score(self, trend_analysis, momentum_analysis, sr_analysis):
        """计算技术面综合评分"""
        try:
            trend_weight = 0.4
            momentum_weight = 0.4
            position_weight = 0.2
            
            total_score = (
                trend_analysis.get('trend_score', 50) * trend_weight +
                momentum_analysis.get('momentum_score', 50) * momentum_weight +
                sr_analysis.get('position_score', 50) * position_weight
            )
            
            return round(total_score, 1)
            
        except Exception as e:
            print(f"计算技术评分失败: {e}")
            return 50.0
            
    def analyze_single_stock(self, stock_info):
        """分析单只股票"""
        stock_code = stock_info['code']
        stock_name = stock_info['name']
        
        print(f"\n🔍 技术分析: {stock_code} {stock_name}")
        print("-" * 60)
        
        # 获取历史数据
        stock_data = self.get_historical_data(stock_code)
        if stock_data is None:
            print(f"   ❌ 无法获取历史数据")
            return None
            
        print(f"   ✅ 获取到 {len(stock_data)} 天历史数据")
        
        # 计算技术指标
        indicators = self.calculate_technical_indicators(stock_data)
        if not indicators:
            print(f"   ❌ 技术指标计算失败")
            return None
            
        # 趋势分析
        trend_analysis = self.analyze_trend_direction(stock_data, indicators)
        print(f"   📊 趋势分析: {trend_analysis['trend']} (评分: {trend_analysis['trend_score']})")
        print(f"      当前价: {trend_analysis['current_price']:.2f}, MA5: {trend_analysis['ma5']:.2f}, MA20: {trend_analysis['ma20']:.2f}")
        
        # 动量分析
        momentum_analysis = self.analyze_momentum(indicators)
        print(f"   ⚡ 动量分析: RSI {momentum_analysis['rsi_signal']}({momentum_analysis['rsi_value']:.1f}), MACD {momentum_analysis['macd_signal']}")
        print(f"      动量评分: {momentum_analysis['momentum_score']:.1f}")
        
        # 支撑阻力分析
        sr_analysis = self.analyze_support_resistance(stock_data, indicators)
        print(f"   🎯 位置分析: {sr_analysis['position_desc']} (评分: {sr_analysis['position_score']})")
        print(f"      支撑位: {sr_analysis['support_level']:.2f}, 阻力位: {sr_analysis['resistance_level']:.2f}")
        
        # 综合技术评分
        technical_score = self.calculate_technical_score(trend_analysis, momentum_analysis, sr_analysis)
        print(f"   🏆 技术评分: {technical_score}/100")
        
        # 返回分析结果
        result = {
            **stock_info,
            'technical_score': technical_score,
            'trend_analysis': trend_analysis,
            'momentum_analysis': momentum_analysis,
            'sr_analysis': sr_analysis,
            'data_points': len(stock_data)
        }
        
        return result
        
    def run_technical_analysis(self):
        """运行技术分析系统"""
        self.print_header("第三步：技术分析系统 - 深度技术面分析")
        
        # 加载筛选结果
        screened_stocks = self.load_screening_results()
        if not screened_stocks:
            print("❌ 无法加载筛选结果，请先执行第二步")
            return []
            
        print(f"📋 开始对 {len(screened_stocks)} 只候选股票进行技术分析...")
        
        technical_results = []
        
        for i, stock_info in enumerate(screened_stocks, 1):
            print(f"\n[{i:2d}/{len(screened_stocks)}] 技术分析进度")
            
            result = self.analyze_single_stock(stock_info)
            if result:
                technical_results.append(result)
                
        # 按技术评分排序
        technical_results.sort(key=lambda x: x['technical_score'], reverse=True)
        
        # 生成技术分析报告
        self.generate_technical_report(technical_results)
        
        return technical_results
        
    def generate_technical_report(self, technical_results):
        """生成技术分析报告"""
        print(f"\n📊 技术分析结果统计:")
        print(f"   • 分析股票数量: {len(technical_results)}")
        
        if len(technical_results) > 0:
            avg_score = sum(r['technical_score'] for r in technical_results) / len(technical_results)
            print(f"   • 平均技术评分: {avg_score:.1f}")
            
            print(f"\n🏆 技术分析TOP10:")
            print(f"{'排名':<4} {'代码':<8} {'名称':<12} {'筛选评分':<8} {'技术评分':<8} {'趋势':<12} {'动量':<8}")
            print("-" * 75)
            
            for i, result in enumerate(technical_results[:10], 1):
                trend = result['trend_analysis']['trend']
                momentum = f"{result['momentum_analysis']['momentum_score']:.1f}"
                print(f"{i:<4} {result['code']:<8} {result['name']:<12} "
                      f"{result['screening_score']:<8.1f} {result['technical_score']:<8.1f} "
                      f"{trend:<12} {momentum:<8}")
                      
            # 推荐技术面强势股票
            print(f"\n🎯 技术面强势股票 (技术评分>70):")
            strong_stocks = [r for r in technical_results if r['technical_score'] > 70]
            for i, stock in enumerate(strong_stocks[:8], 1):
                print(f"   {i}. {stock['code']} {stock['name']} - 技术评分: {stock['technical_score']:.1f} ({stock['trend_analysis']['trend']})")
                
            if not strong_stocks:
                print(f"   暂无技术评分>70的股票，建议等待更好的技术面机会")
                
        else:
            print(f"   ⚠️ 没有完成技术分析的股票")
            
    def save_technical_results(self, technical_results, filename="technical_analysis_results.csv"):
        """保存技术分析结果"""
        if technical_results:
            # 简化数据结构用于保存
            save_data = []
            for result in technical_results:
                save_record = {
                    'code': result['code'],
                    'name': result['name'],
                    'current_price': result['current_price'],
                    'market_cap': result['market_cap'],
                    'pe_ratio': result['pe_ratio'],
                    'screening_score': result['screening_score'],
                    'technical_score': result['technical_score'],
                    'trend': result['trend_analysis']['trend'],
                    'trend_score': result['trend_analysis']['trend_score'],
                    'momentum_score': result['momentum_analysis']['momentum_score'],
                    'position_score': result['sr_analysis']['position_score'],
                    'has_dividend': result['has_dividend'],
                    'dividend_count': result['dividend_count']
                }
                save_data.append(save_record)
                
            df = pd.DataFrame(save_data)
            df.to_csv(filename, index=False, encoding='utf-8-sig')
            print(f"\n💾 技术分析结果已保存到 {filename}")
            return filename
        return None

if __name__ == "__main__":
    # 创建技术分析系统实例
    tech_analyzer = TechnicalAnalysisSystem()
    
    # 执行技术分析
    results = tech_analyzer.run_technical_analysis()
    
    # 保存结果
    tech_analyzer.save_technical_results(results)
    
    print(f"\n🎉 第三步：技术分析系统执行完成！")
    print(f"   • 成功分析了 {len(results)} 只股票的技术面")
    print(f"   • 准备进入第四步：基本面分析系统")
